package com.bite.lesson2;

public class Demo_04 {
    // 累加次数
    public static int num = 10000;
    // 实例化执行累加的类
    public static Counter counter = new Counter();

    public static void main(String[] args) throws InterruptedException {
        // 定义两个线程
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < num; i++) {
                counter.increase();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < num; i++) {
                counter.increase();
            }
        });

        // 启动线程
        t1.start();
        t2.start();
        // 等待线程执行完成
        t1.join();
        t2.join();
        System.out.println("累加结果 = " + counter.count);

    }
}

// 定义一个执行累加的类
class Counter {
    // 初始值为0
    public int count = 0;

    // 累加方法，用synchronized保证线程安全
    public synchronized void increase () {
        count++;
    }
}
